﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using AutoWelding.Models;

using MySql.Data.MySqlClient;

namespace AutoWelding.DAL
{
    public class LoginDAL
    {
        /// <summary>
        /// 检查用户是否存在（登陆验证）
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="identity"></param>
        /// 
        public UserModel CheckUser(string username, string password)
        {
            try
            {
                string sql = @"
            SELECT * FROM user_info 
            WHERE user_name = @UserName 
              AND user_password = @Password 
              AND is_delete = 1 
              AND user_status = 1";

                List<MySqlParameter> parameters = new List<MySqlParameter>
        {
            new MySqlParameter("@UserName", MySqlDbType.VarChar) { Value = username },
            new MySqlParameter("@Password", MySqlDbType.VarChar) { Value = password }
        };

                // 使用 ExecuteQuery 获取用户数据
                var users = MysqlHelp.ExecuteQuery<UserModel>(sql,
                    reader => new UserModel
                    {
                        UserId = Convert.ToInt32(reader["user_id"]),
                        UserName = reader["user_name"].ToString(),
                        NickName = reader["nick_name"].ToString(),
                        UserIdentity = Convert.ToInt32(reader["user_identity"]),
                        UserStatus = Convert.ToInt32(reader["user_status"]),
                        IsDelete = Convert.ToInt32(reader["is_delete"]),
                        CreateTime = Convert.ToDateTime(reader["create_time"]),
                        UpdateTime = reader["update_time"] != DBNull.Value ? Convert.ToDateTime(reader["update_time"]) : (DateTime?)null,
                        Remark = reader["remark"]?.ToString()
                    },
                    parameters.ToArray());

                return users.FirstOrDefault(); // 如果没有匹配用户则返回 null
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库发生错误！" + ex.Message);
                return null;
            }
        }
    }
}
